package com.ideaaedi.zoo.diy.artifact.openfeign.holder;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.ideaaedi.zoo.commonbase.context.DefaultZcProvider;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * 本次feign调用 请求信息
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
@Slf4j
public class OnceFeignInfoHolder {
    
    /**
     * 会话级临时数据域值
     * <p>
     * TransmittableThreadLocal相关说明可参考{@link DefaultZcProvider#contextThreadLocal}注释
     * </p>
     */
    @Getter
    public static final ThreadLocal<ConcurrentLinkedDeque<OnceFeignInfo>> TEMP_FEIGN_HOLDER = new TransmittableThreadLocal<>() {
        
        @Override
        protected ConcurrentLinkedDeque<OnceFeignInfo> initialValue() {
            return new ConcurrentLinkedDeque<>();
        }
        
        @Override
        public ConcurrentLinkedDeque<OnceFeignInfo> copy(ConcurrentLinkedDeque<OnceFeignInfo> parentValue) {
            return doCopy(parentValue);
        }
        
        @Override
        protected ConcurrentLinkedDeque<OnceFeignInfo> childValue(ConcurrentLinkedDeque<OnceFeignInfo> parentValue) {
            return doCopy(parentValue);
        }
        
        /**
         * (non-javadoc)
         */
        private ConcurrentLinkedDeque<OnceFeignInfo> doCopy(ConcurrentLinkedDeque<OnceFeignInfo> parentValue) {
            if (parentValue == null) {
                return new ConcurrentLinkedDeque<>();
            }
            return new ConcurrentLinkedDeque<>(
                    parentValue.stream().map(item -> {
                        if (item == null) {
                            return null;
                        }
                        return OnceFeignInfo.of(item.getUrlPrefix(), item.getHeaders());
                    }).toList()
            );
        }
    };
    
}